package com.xtoneict;

import com.xtoneict.framework.expands.http.okhttpclient.SimpleRequestBuilder;
import com.xtoneict.framework.expands.orm.api.Database;
import com.xtoneict.framework.util.StringUtils;
import com.xtoneict.framework.util.spring.ApplicationContext;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;


@SpringBootApplication
public class Test1 {

    /**
     * @param args
     */

    /*
    public static void main(String[] args) {
        SpringApplication.run(Test1.class, args);

        Database database = ApplicationContext.getCurrent().getBean(Database.class);
        List<LinkedHashMap> rows = database.getTable("districtsx", LinkedHashMap.class).createQuery().is("level", "district").list();
        for (LinkedHashMap row : rows) {
            String adcode = (String) row.get("adcode");
            List<Area> areas = test(adcode);
            if (areas == null || areas.size() == 0) {
                continue;
            }
            List<LinkedHashMap> rows1 = database.getTable("districtsx", LinkedHashMap.class).createQuery().is("adcode", adcode).list();
            List<Integer> ids = new ArrayList<>();
            rows1.forEach(temp -> {
                ids.add((Integer) temp.get("districtid"));
            });
            for (Area area : areas) {
                database.getTable("districtsx", LinkedHashMap.class).createUpdate()
                        .is("name", area.getName())
                        .in("districtId", ids)
                        .set(new LinkedHashMap<String, Object>() {{
                            put("adcode", area.getCode());
                        }}).exec();
                System.out.println(area.toString());
            }
        }
    }*/


    public static void main(String[] args) {
        SpringApplication.run(Test1.class, args);

        Database database = ApplicationContext.getCurrent().getBean(Database.class);
        List<LinkedHashMap> rows = database.getTable("districtsx", LinkedHashMap.class).createQuery().is("level", "district").list();
        for (LinkedHashMap row : rows) {
            String adcode = (String) row.get("adcode");
            List<Area> areas = test1(adcode);
            if (areas == null || areas.size() == 0) {
                continue;
            }
            List<LinkedHashMap> rows1 = database.getTable("districtsx", LinkedHashMap.class).createQuery().is("adcode", adcode).list();
            List<Integer> ids = new ArrayList<>();
            rows1.forEach(temp -> {
                ids.add((Integer) temp.get("districtid"));
            });
            for (Area area : areas) {
                database.getTable("districtsx", LinkedHashMap.class).createUpdate()
                        .is("name", area.getName())
                        .in("districtId", ids)
                        .set(new LinkedHashMap<String, Object>() {{
                            put("adcode", area.getCode());
                        }}).exec();
                System.out.println(area.toString());
            }
        }
    }

    public static List<Area> test1(String adcode) {

        List<Area> result = new ArrayList<>();
        SimpleRequestBuilder builder = new SimpleRequestBuilder();
        try {
            String httpString = builder.http("https://xingzhengquhua.bmcx.com/" + adcode + "000000__xingzhengquhua/").get().asString();

            Document document = Jsoup.parse(httpString);
            document.getElementsByTag("table");
            List<Element> tables = getElementByAttr(document, "table", "cellpadding", "8");
            if(tables == null || tables.size() == 0){
                return new ArrayList<>();
            }
            Elements trs = tables.get(0).getElementsByTag("tr");
            for (Element tr : trs) {
                Elements tds = tr.getElementsByTag("td");
                List<String> datas = new ArrayList<>();
                if (tr.toString().contains("撤销")) {
                    break;
                }
                for (Element td : tds) {

                    Elements as = td.getElementsByTag("a");
                    if (as.size() == 1) {
                        String name = as.get(0).ownText();
                        if (StringUtils.isNotEmpty(name)) {
                            datas.add(name);
                        }
                    }
                }
                if (datas.size() > 0) {
                    Area area = Area.builder().name(datas.get(0)).code(datas.get(1)).build();
                    result.add(area);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }


    public static List<Area> test(String adcode) {

        List<Area> result = new ArrayList<>();
        System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://xingzhengquhua.bmcx.com/" + adcode + "000000__xingzhengquhua/");

            List<WebElement> tables = getElementByAttr(driver, "table", "cellpadding", "8");

            List<WebElement> trs = tables.get(0).findElements(By.tagName("tr"));
            for (WebElement tr : trs) {
                List<WebElement> tds = tr.findElements(By.tagName("td"));
                List<String> datas = new ArrayList<>();
                if (tr.getAttribute("innerHTML").contains("撤销")) {
                    break;
                }
                for (WebElement td : tds) {

                    List<WebElement> as = td.findElements(By.tagName("a"));
                    if (as.size() == 1) {
                        String name = as.get(0).getAttribute("innerHTML");
                        if (StringUtils.isNotEmpty(name)) {
                            datas.add(name);
                        }
                    }
                }
                if (datas.size() > 0) {
                    Area area = Area.builder().name(datas.get(0)).code(datas.get(1)).build();
                    result.add(area);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            driver.quit();
        }

        return result;

    }

    static List<WebElement> getElementByAttr(WebDriver driver, String tag, String dataAttr, String dataAttrValue) {
        List<WebElement> aElements = driver.findElements(By.tagName(tag));
        List<WebElement> aEle = new ArrayList<WebElement>();
        for (WebElement element : aElements) {
            String ele = element.getAttribute(dataAttr);
            if (ele.equals(dataAttrValue)) {
                aEle.add(element);
            }
        }
        return aEle;
    }


    static List<Element> getElementByAttr(Document document, String tag, String dataAttr, String dataAttrValue) {
        Elements aElements = document.getElementsByTag(tag);
        List<Element> aEle = new ArrayList<Element>();
        for (Element element : aElements) {
            String ele = element.attr(dataAttr);
            if (ele.equals(dataAttrValue)) {
                aEle.add(element);
            }
        }
        return aEle;
    }


}